#include "client.h"
#include <ctype.h>
#include <dirent.h>

void singlewordcounts(char * filename,int cs[],int CS[])
{
    
            FILE *fp;
	    char ch;
	    int c=0,i=0;
	    if((fp=fopen(filename,"r"))==NULL)
	    {
	    printf("open this file fail!\n");
	    exit(0);
	    } 

	    while((ch=fgetc(fp))!=EOF)
	    {
	    if(ch>='a'&&ch<='z')
 	    {cs[ch-'a']++;c++;}
	    else 
	    if(ch>='A'&&ch<='Z')
	    {CS[ch-'A']++;c++;}
	    } 

            printf("Docment  name is %s,  the number of words is %d\n",filename,c);
	    for(i=0;i<N;i++)
	    if(cs[i]!=0)
	    printf("The number of %c is %d \n",i+'a',cs[i]); 

	    for(i=0;i<N;i++)
	    if(CS[i]!=0)
	    printf("The number of %c is %d \n",i+'A',CS[i]);
}

void printdir(char *dir)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;
    int cs[N] = {0},CS[N]={0},c=0;
    int i;
    char ch;
    pid_t pid;
    int server_fifo_fd, client_fifo_fd;
    struct data_to_pass_st my_data;
    if((dp = opendir(dir)) == NULL) {
        return;
    }
    chdir(dir);
    while((entry = readdir(dp)) != NULL) {
        lstat(entry->d_name,&statbuf);
        if(S_ISDIR(statbuf.st_mode)) {
            /* Found a directory, but ignore . and .. */
            if(strcmp(".",entry->d_name) == 0 || 
                strcmp("..",entry->d_name) == 0)
                continue;

            /* Recurse at a new indent level */
            printdir(entry->d_name);
        }
        else
        {
	    pid = fork();
	    if(pid == 0)
	    {
	    singlewordcounts(entry->d_name,cs,CS);
	    server_fifo_fd = open(SERVER_FIFO_NAME, O_WRONLY);
	    if(server_fifo_fd == -1)
	    {
		fprintf(stderr,"Server fifo failure\n");
		exit(EXIT_FAILURE);
 	    }
	    my_data.client_pid = getpid();
	    for(i=0;i<N;i++)
	    {
             my_data.cs[i]=cs[i];
	     my_data.CS[i]=CS[i];
	    }
	    my_data.flag = 1;
	    write(server_fifo_fd,&my_data,sizeof(my_data));

	    return;
	    }
	    wait(pid,NULL,0);
    }
    }
    chdir("..");
    closedir(dp);
}


int main(int argc , char *argv[])
{
    char *topdir, pwd[2]=".";
    if (argc != 2)
        topdir=pwd;
    else
        topdir=argv[1];

    printf("The dirctory is %s\n",topdir);
    printdir(topdir);
    printf("done.\n");

    exit(0);
}

